<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DLNA设备管理器</title>
    <style>
        /* 原有样式保持不变，新增以下样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #2c3e50, #34495e);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
        }

        .header .subtitle {
            font-size: 1.2em;
            opacity: 0.9;
        }

        .content {
            padding: 30px;
        }

        .card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 25px;
            margin-bottom: 20px;
            border-left: 5px solid #3498db;
        }

        .card.status-card {
            border-left-color: #2ecc71;
        }

        .card.video-card {
            border-left-color: #e74c3c;
        }

        .card.info-card {
            border-left-color: #f39c12;
        }

        .card h3 {
            color: #2c3e50;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 1.3em;
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }

        .info-item {
            background: white;
            padding: 15px;
            border-radius: 8px;
            border: 1px solid #e9ecef;
        }

        .info-item strong {
            color: #495057;
            display: block;
            margin-bottom: 5px;
            font-size: 0.9em;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .info-item .value {
            color: #2c3e50;
            font-size: 1.1em;
            font-weight: 600;
        }

        .ip-address {
            color: #e74c3c;
            font-weight: bold;
            font-size: 1.3em;
        }

        .status-indicator {
            display: inline-block;
            padding: 8px 16px;
            background: #95a5a6;
            color: white;
            border-radius: 20px;
            font-weight: bold;
            margin-top: 10px;
        }

        .status-indicator.waiting {
            background: #95a5a6;
        }

        .status-indicator.playing {
            background: #2ecc71;
            animation: pulse 2s infinite;
        }

        .status-indicator.stopped {
            background: #e74c3c;
        }

        .video-details {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-top: 15px;
            border: 1px solid #e9ecef;
        }

        .video-title {
            font-size: 1.4em;
            color: #2c3e50;
            margin-bottom: 10px;
            font-weight: bold;
        }

        .video-url {
            color: #7f8c8d;
            word-break: break-all;
            font-family: monospace;
            background: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            border: 1px solid #e9ecef;
        }

        .instructions {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
        }

        .instructions h4 {
            color: #856404;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .instructions ol {
            margin-left: 20px;
            color: #856404;
        }

        .instructions li {
            margin-bottom: 10px;
            line-height: 1.5;
        }

        .last-update {
            text-align: center;
            color: #7f8c8d;
            font-size: 0.9em;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #e9ecef;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.7; }
            100% { opacity: 1; }
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .header h1 {
                font-size: 2em;
                flex-direction: column;
                gap: 5px;
            }

            .content {
                padding: 20px;
            }

            .info-grid {
                grid-template-columns: 1fr;
            }
        }

        /* 图标样式 */
        .icon {
            font-size: 1.2em;
        }

        .no-video {
            text-align: center;
            color: #7f8c8d;
            padding: 40px;
            font-style: italic;
        }
        .device-management {
            margin-top: 30px;
        }

        .device-list {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-top: 15px;
            border: 1px solid #e9ecef;
            max-height: 400px;
            overflow-y: auto;
        }

        .device-item {
            padding: 15px;
            border: 1px solid #e1e8ed;
            border-radius: 8px;
            margin-bottom: 10px;
            background: #f8f9fa;
            transition: all 0.3s ease;
        }

        .device-item:hover {
            background: #e3f2fd;
            border-color: #2196f3;
        }

        .device-header {
            display: flex;
            justify-content: between;
            align-items: center;
            margin-bottom: 10px;
        }

        .device-name {
            font-weight: bold;
            font-size: 1.1em;
            color: #2c3e50;
        }

        .device-type {
            background: #3498db;
            color: white;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 0.8em;
        }

        .device-type.virtual {
            background: #2ecc71;
        }

        .device-type.physical {
            background: #e74c3c;
        }

        .device-info {
            font-size: 0.9em;
            color: #7f8c8d;
            margin-bottom: 10px;
        }

        .device-actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .action-btn {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.85em;
            transition: all 0.3s ease;
        }

        .action-btn.play {
            background: #2ecc71;
            color: white;
        }

        .action-btn.stop {
            background: #e74c3c;
            color: white;
        }

        .action-btn.discover {
            background: #3498db;
            color: white;
        }

        .action-btn:hover {
            opacity: 0.9;
            transform: translateY(-1px);
        }

        .video-input-section {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-top: 20px;
            border: 1px solid #e9ecef;
        }

        .input-group {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }

        .input-group input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .tab-container {
            margin-top: 20px;
        }

        .tabs {
            display: flex;
            border-bottom: 2px solid #3498db;
            margin-bottom: 20px;
        }

        .tab {
            padding: 12px 24px;
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-bottom: none;
            border-radius: 8px 8px 0 0;
            cursor: pointer;
            margin-right: 5px;
        }

        .tab.active {
            background: #3498db;
            color: white;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8em;
            font-weight: bold;
            margin-left: 10px;
        }

        .status-online {
            background: #2ecc71;
            color: white;
        }

        .status-offline {
            background: #95a5a6;
            color: white;
        }
    </style>
</head>
<body>
<div class="container">
    <!-- 头部 -->
    <div class="header">
        <h1>
            <span class="icon">📺</span>
            DLNA设备管理器
        </h1>
        <div class="subtitle">虚拟DLNA接收器 + 真实机顶盒推送</div>
    </div>

    <!-- 内容区域 -->
    <div class="content">
        <!-- 标签页 -->
        <div class="tab-container">
            <div class="tabs">
                <div class="tab active" onclick="switchTab('virtual')">虚拟DLNA设备</div>
                <div class="tab" onclick="switchTab('physical')">真实机顶盒管理</div>
                <div class="tab" onclick="switchTab('push')">视频推送</div>
            </div>

            <!-- 虚拟DLNA设备标签页 -->
            <div id="virtual-tab" class="tab-content active">
                <!-- 原有虚拟DLNA设备内容保持不变 -->
                <div class="card">
                    <h3><span class="icon">🔧</span> 设备信息</h3>
                    <div class="info-grid">
                        <div class="info-item">
                            <strong>IP地址</strong>
                            <div class="value ip-address" th:text="${deviceIp} + ':' + ${devicePort}">192.168.1.100:8191</div>
                        </div>
                        <div class="info-item">
                            <strong>设备名称</strong>
                            <div class="value">SpringBoot DLNA Receiver</div>
                        </div>
                        <div class="info-item">
                            <strong>设备类型</strong>
                            <div class="value">MediaRenderer</div>
                        </div>
                        <div class="info-item">
                            <strong>服务状态</strong>
                            <div class="value" style="color: #2ecc71;">● 运行中</div>
                        </div>
                    </div>
                </div>

                <!-- 状态卡片 -->
                <div class="card status-card">
                    <h3><span class="icon">📊</span> 播放状态</h3>
                    <div th:if="${status != null and !#strings.isEmpty(status)}">
                        <div th:class="${'status-indicator ' +
                (#strings.contains(status, '播放') ? 'playing' :
                 #strings.contains(status, '停止') ? 'stopped' :
                 'waiting')}">
                            <span th:text="${status}">等待投屏...</span>
                        </div>
                    </div>
                    <div th:unless="${status != null and !#strings.isEmpty(status)}">
                        <div class="status-indicator waiting">
                            <span>等待投屏...</span>
                        </div>
                    </div>
                </div>

                <!-- 视频信息卡片 -->
                <div class="card video-card">
                    <h3><span class="icon">🎬</span> 当前播放内容</h3>
                    <div class="video-details">
                        <div class="video-title">未知视频</div>
                        <div class="video-url">-</div>
                    </div>
                </div>


                <!-- 设备控制卡片 -->
                <div class="card control-card">
                    <h3><span class="icon">🎮</span> 虚拟设备控制</h3>
                    <div class="control-buttons">
                        <button class="btn btn-primary" onclick="broadcastPresence()">
                            <span class="icon">📢</span> 广播设备存在
                        </button>
                        <button class="btn btn-secondary" onclick="checkStatus()">
                            <span class="icon">🔍</span> 检查设备状态
                        </button>
                        <button class="btn btn-info" onclick="location.reload()">
                            <span class="icon">🔄</span> 刷新页面
                        </button>
                    </div>
                    <div id="controlResult" class="result-message"></div>
                </div>
            </div>

            <!-- 真实机顶盒管理标签页 -->
            <div id="physical-tab" class="tab-content">
                <div class="card">
                    <h3><span class="icon">📡</span> 局域网DLNA设备发现</h3>
                    <div class="control-buttons">
                        <button class="btn btn-primary" onclick="discoverDevices()">
                            <span class="icon">🔍</span> 扫描设备
                        </button>
                        <button class="btn btn-secondary" onclick="clearDeviceList()">
                            <span class="icon">🗑️</span> 清空列表
                        </button>
                    </div>
                    <div id="discoverResult" class="result-message"></div>
                </div>

                <div class="device-list" id="deviceList">
                    <div class="no-devices" id="noDevicesMessage">
                        <p style="text-align: center; color: #7f8c8d; padding: 40px;">
                            <span class="icon">🔍</span><br>
                            暂无发现的设备<br>
                            <small>点击"扫描设备"按钮发现局域网中的DLNA机顶盒</small>
                        </p>
                    </div>
                </div>
            </div>

            <!-- 视频推送标签页 -->
            <div id="push-tab" class="tab-content">
                <div class="card">
                    <h3><span class="icon">🎬</span> 视频推送</h3>

                    <div class="video-input-section">
                        <div class="input-group">
                            <input type="text" id="videoUrl" placeholder="输入视频URL (例如: http://example.com/video.mp4)" style="flex: 1;">
                            <button class="btn btn-primary" onclick="testVideoUrl()">测试URL</button>
                        </div>

                        <div class="input-group">
                            <select id="targetDevice" style="flex: 1; padding: 10px; border: 1px solid #ddd; border-radius: 4px;">
                                <option value="">选择目标设备</option>
                            </select>
                            <button class="btn btn-success" onclick="pushVideo()">推送视频</button>
                            <button class="btn btn-warning" onclick="stopPlayback()">停止播放</button>
                        </div>

                        <div id="pushResult" class="result-message"></div>
                    </div>
                </div>

                <div class="card">
                    <h3><span class="icon">📋</span> 示例视频URL</h3>
                    <div style="font-size: 0.9em; color: #7f8c8d;">
                        <p>测试用视频URL：</p>
                        <ul>
                            <li>https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4</li>
                            <li>https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4</li>
                            <li>http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <!-- 原有使用说明和支持的APP卡片保持不变 -->
        <div class="instructions">
            <h4><span class="icon">📱</span> 使用说明</h4>
            <ol>
                <li><strong>虚拟DLNA设备</strong>: 手机APP可以投屏到本虚拟设备</li>
                <li><strong>真实机顶盒管理</strong>: 扫描并控制局域网中的真实DLNA设备</li>
                <li><strong>视频推送</strong>: 主动推送在线视频到选择的设备</li>
            </ol>
        </div>

        <div class="last-update">
            页面最后更新: <span th:text="${#dates.format(#dates.createNow(), 'yyyy-MM-dd HH:mm:ss')}">2024-01-01 12:00:00</span>
            |
            <a href="javascript:location.reload()" style="color: #3498db; text-decoration: none;">🔄 刷新页面</a>
        </div>
    </div>
</div>

<script>
    // 标签页切换功能
    function switchTab(tabName) {
        // 隐藏所有标签页内容
        document.querySelectorAll('.tab-content').forEach(tab => {
            tab.classList.remove('active');
        });

        // 移除所有标签的active状态
        document.querySelectorAll('.tab').forEach(tab => {
            tab.classList.remove('active');
        });

        // 显示选中的标签页
        document.getElementById(tabName + '-tab').classList.add('active');

        // 设置选中的标签为active
        event.target.classList.add('active');

        // 如果是设备管理标签，自动扫描设备
        if (tabName === 'physical') {
           // discoverDevices();
        }
    }

    // 发现DLNA设备
    async function discoverDevices() {
        const button = event.target;
        const originalText = button.innerHTML;

        button.innerHTML = '<span class="icon">🔍</span> 扫描中...';
        button.disabled = true;

        try {
            const response = await fetch('/api/dlna/discover');
            const devices = await response.json();

            displayDevices(devices);

            const resultDiv = document.getElementById('discoverResult');
            if (devices.length > 0) {
                resultDiv.textContent = `✅ 发现 ${devices.length} 个DLNA设备`;
                resultDiv.className = 'result-message success';
            } else {
                resultDiv.textContent = '⚠️ 未发现任何DLNA设备';
                resultDiv.className = 'result-message error';
            }
            resultDiv.style.display = 'block';

        } catch (error) {
            const resultDiv = document.getElementById('discoverResult');
            resultDiv.textContent = '❌ 扫描失败: ' + error.message;
            resultDiv.className = 'result-message error';
            resultDiv.style.display = 'block';
        } finally {
            button.innerHTML = originalText;
            button.disabled = false;
        }
    }

    // 显示设备列表
    function displayDevices(devices) {
        const deviceList = document.getElementById('deviceList');
        const noDevicesMessage = document.getElementById('noDevicesMessage');
        const targetDeviceSelect = document.getElementById('targetDevice');

        if (devices.length === 0) {
            noDevicesMessage.style.display = 'block';
            deviceList.innerHTML = '';
            return;
        }

        noDevicesMessage.style.display = 'none';

        // 清空设备列表和选择框
        deviceList.innerHTML = '';
        targetDeviceSelect.innerHTML = '<option value="">选择目标设备</option>';

        devices.forEach((device, index) => {
            // 添加到设备列表
            const deviceItem = document.createElement('div');
            deviceItem.className = 'device-item';
            deviceItem.innerHTML = `
                    <div class="device-header">
                        <div class="device-name">${device.friendlyName || '未知设备'}</div>
                        <div class="device-type physical">真实设备</div>
                    </div>
                    <div class="device-info">
                        IP: ${device.ip} | 类型: ${device.deviceType || 'MediaRenderer'}
                    </div>
                    <div class="device-actions">
                        <button class="action-btn play" onclick="pushToDevice('${device.location}', '${device.friendlyName || '设备'}')">
                            🎬 推送测试视频
                        </button>
                        <button class="action-btn discover" onclick="showDeviceInfo('${device.location}')">
                            ℹ️ 设备信息
                        </button>
                    </div>
                `;
            deviceList.appendChild(deviceItem);

            // 添加到选择框
            const option = document.createElement('option');
            option.value = device.location;
            option.textContent = `${device.friendlyName || '未知设备'} (${device.ip})`;
            targetDeviceSelect.appendChild(option);
        });
    }

    // 清空设备列表
    function clearDeviceList() {
        const deviceList = document.getElementById('deviceList');
        const noDevicesMessage = document.getElementById('noDevicesMessage');
        const targetDeviceSelect = document.getElementById('targetDevice');

        deviceList.innerHTML = '';
        noDevicesMessage.style.display = 'block';
        targetDeviceSelect.innerHTML = '<option value="">选择目标设备</option>';

        const resultDiv = document.getElementById('discoverResult');
        resultDiv.textContent = '✅ 设备列表已清空';
        resultDiv.className = 'result-message success';
        resultDiv.style.display = 'block';
    }

    // 推送到指定设备
    async function pushToDevice(deviceLocation, deviceName) {
        const testUrl = 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4';

        try {
            const response = await fetch(`/api/dlna/push?deviceLocation=${encodeURIComponent(deviceLocation)}&videoUrl=${encodeURIComponent(testUrl)}`);
            const result = await response.text();

            const resultDiv = document.getElementById('pushResult');
            if (response.ok) {
                resultDiv.textContent = `✅ 视频已推送到 ${deviceName}`;
                resultDiv.className = 'result-message success';
            } else {
                resultDiv.textContent = `❌ 推送失败: ${result}`;
                resultDiv.className = 'result-message error';
            }
            resultDiv.style.display = 'block';

        } catch (error) {
            const resultDiv = document.getElementById('pushResult');
            resultDiv.textContent = '❌ 推送失败: ' + error.message;
            resultDiv.className = 'result-message error';
            resultDiv.style.display = 'block';
        }
    }

    // 推送视频
    async function pushVideo() {
        const deviceLocation = document.getElementById('targetDevice').value;
        const videoUrl = document.getElementById('videoUrl').value;

        if (!deviceLocation) {
            showPushResult('❌ 请选择目标设备', false);
            return;
        }

        if (!videoUrl) {
            showPushResult('❌ 请输入视频URL', false);
            return;
        }

        try {
            const response = await fetch(`/api/dlna/push?deviceLocation=${encodeURIComponent(deviceLocation)}&videoUrl=${encodeURIComponent(videoUrl)}`);
            const result = await response.text();

            if (response.ok) {
                showPushResult('✅ 视频推送成功', true);
            } else {
                showPushResult(`❌ 推送失败: ${result}`, false);
            }

        } catch (error) {
            showPushResult('❌ 推送失败: ' + error.message, false);
        }
    }

    // 停止播放
    async function stopPlayback() {
        // 这里需要根据您的实现添加停止播放的逻辑
        showPushResult('⏹️ 停止播放功能待实现', false);
    }

    // 测试视频URL
    async function testVideoUrl() {
        const videoUrl = document.getElementById('videoUrl').value;
        if (!videoUrl) {
            showPushResult('❌ 请输入视频URL', false);
            return;
        }

        try {
            const response = await fetch(videoUrl, { method: 'HEAD' });
            if (response.ok) {
                showPushResult('✅ 视频URL可访问', true);
            } else {
                showPushResult(`⚠️ 视频URL返回状态: ${response.status}`, false);
            }
        } catch (error) {
            showPushResult('❌ 视频URL无法访问: ' + error.message, false);
        }
    }

    // 显示设备信息
    function showDeviceInfo(deviceLocation) {
        window.open(deviceLocation, '_blank');
    }

    // 显示推送结果
    function showPushResult(message, isSuccess) {
        const resultDiv = document.getElementById('pushResult');
        resultDiv.textContent = message;
        resultDiv.className = isSuccess ? 'result-message success' : 'result-message error';
        resultDiv.style.display = 'block';
    }

    // 原有的虚拟设备控制函数保持不变
    // 控制功能
    async function broadcastPresence() {
        const button = event.target;
        const originalText = button.innerHTML;

        button.innerHTML = '<span class="icon">⏳</span> 广播中...';
        button.disabled = true;

        try {
            const response = await fetch('/api/broadcast', { method: 'POST' });
            const result = await response.text();

            showResult(result, true);
            console.log('广播成功:', result);
        } catch (error) {
            showResult('广播失败: ' + error.message, false);
            console.error('广播失败:', error);
        } finally {
            button.innerHTML = originalText;
            button.disabled = false;
        }
    }

    async function checkStatus() {
        const button = event.target;
        const originalText = button.innerHTML;

        button.innerHTML = '<span class="icon">⏳</span> 检查中...';
        button.disabled = true;

        try {
            const response = await fetch('/api/status', { method: 'POST' });
            const result = await response.text();

            showResult(result, true);
            console.log('状态检查:', result);
        } catch (error) {
            showResult('状态检查失败: ' + error.message, false);
            console.error('状态检查失败:', error);
        } finally {
            button.innerHTML = originalText;
            button.disabled = false;
        }
    }

    function showResult(message, isSuccess) {
        const resultDiv = document.getElementById('controlResult');
        resultDiv.textContent = message;
        resultDiv.className = isSuccess ? 'result-message success' : 'result-message error';

        // 3秒后自动隐藏
        setTimeout(() => {
            resultDiv.style.display = 'none';
        }, 5000);
    }

    // 页面加载后自动扫描设备
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DLNA设备管理器已加载');
    });

    // 每10秒自动刷新状态
    setInterval(function() {
        fetch('/getMovie')
            .then(response => response.json())
            .then(data => {
                // 更新设备信息
                const ipElement = document.querySelector('.ip-address');
                if (ipElement && data.deviceIp) {
                    ipElement.textContent = data.deviceIp + ':' + data.devicePort;
                }

                // 更新状态
                const statusElement = document.querySelector('.status-indicator');
                if (statusElement && data.status) {
                    statusElement.textContent = data.status;

                    // 更新状态样式
                    statusElement.className = 'status-indicator ';
                    if (data.status.includes('等待')) {
                        statusElement.classList.add('waiting');
                    } else if (data.status.includes('播放')) {
                        statusElement.classList.add('playing');
                    } else if (data.status.includes('停止')) {
                        statusElement.classList.add('stopped');
                    } else {
                        statusElement.classList.add('waiting');
                    }
                }

                // 更新视频信息
                const videoCard = document.querySelector('.video-card');
                const noVideoCard = document.querySelector('.no-video');

                if (data.videoUrl) {
                    // 有视频在播放
                    if (noVideoCard) noVideoCard.style.display = 'none';
                    if (videoCard) videoCard.style.display = 'block';

                    // 更新视频标题和URL
                    const videoTitle = document.querySelector('.video-title');
                    const videoUrl = document.querySelector('.video-url');


                    if (data.videoTitle) {
                        videoTitle.textContent = data.videoTitle.length > 10 ? data.videoTitle.substring(0, 10) + '...' : data.videoTitle;
                    }
                    if (data.videoUrl) {
                        videoUrl.textContent = data.videoUrl;
                    }
                } else {
                    // 没有视频在播放
                    if (videoCard) videoCard.style.display = 'none';
                    if (noVideoCard) noVideoCard.style.display = 'block';
                }

                console.log('状态已更新:', data.status);
            })
            .catch(error => console.log('自动刷新检查失败:', error));
    }, 3000);
</script>
</body>
</html>